"""
作者：程序猿
邮箱：1693057533@qq.com
时间：2021-8.txt-21
环境：Python3.6

这是一个进程和网络的综合训练
"""
from socket import *
from multiprocessing import Process

HOST = "0.0.0.0"
PORT = 8888
ADDR = (HOST, PORT)

# 存储用户信息 {name:address}
user = {}


def login(sock, name, addr):
    if name in user or "管理" in name:
        sock.sendto(b"FAIL", addr)
    else:
        sock.sendto(b"OK", addr)
        # 循环通知其他人
        msg = "欢迎 %s 进入聊天室" % name
        for key, value in user.items():
            sock.sendto(msg.encode(), value)
        user[name] = addr  # 添加用户


def chat(sock, name, content):
    msg = "%s : %s" % (name, content)
    for key, value in user.items():
        if key != name:  # 除了自己
            sock.sendto(msg.encode(), value)


def exit(sock, name):
    if name in user:
        del user[name]  # 删除用户
    # 循环通知所有人
    msg = "%s退出了群聊" % name
    for key, value in user.items():
        sock.sendto(msg.encode(), value)


# 子进程负责处理请求
def do_request(sock):
    # 循环接收请求分情况讨论
    while True:
        request, addr = sock.recvfrom(1024)  # 接收请求
        tmp = request.decode().split(' ', 2)  # 解析请求
        if tmp[0] == "LOGIN":
            # tmp ->[LOGIN,name]
            login(sock, tmp[1], addr)
        elif tmp[0] == "CHAT":
            # tmp ->[CHAT,name,content]
            chat(sock, tmp[1], tmp[2])
        elif tmp[0] == "EXIT":
            # tmp ->[EXIT,name]
            exit(sock, tmp[1])


def main():
    sock = socket(AF_INET, SOCK_DGRAM)
    sock.bind(ADDR)
    p = Process(target=do_request, args=(sock,), daemon=True)
    p.start()
    # 父进程发送管理员消息
    while True:
        content = input("管理员消息：")
        if content == "exit":
            break
        msg = "CHAT 管理员消息 " + content
        sock.sendto(msg.encode(), ADDR)


if __name__ == '__main__':
    main()
